package zhoug.common.livedata;

import java.util.concurrent.ConcurrentHashMap;

import androidx.lifecycle.MutableLiveData;

/**
 * @Author: zhoug
 * @Date: 2024-05-21
 * @Description:
 */
public class SingleLiveDataManager {
    private static SingleLiveDataManager instance;//单例
    private final ConcurrentHashMap<String, MutableLiveData> maps;


    private SingleLiveDataManager() {
        maps = new ConcurrentHashMap<>();
    }

    /**
     * 单例
     */
    public static SingleLiveDataManager getInstance() {
        if (null == instance) {
            synchronized (SingleLiveDataManager.class) {
                if (null == instance) {
                    instance = new SingleLiveDataManager();
                }
            }
        }
        return instance;
    }

    public <T> MutableLiveData<T> get(String key) {
        MutableLiveData<T> liveData = null;
        if (maps.size() > 0 && maps.containsKey(key)) {
            liveData = maps.get(key);
        }
        if (liveData == null) {
            liveData = new MutableLiveData<>();
            maps.put(key, liveData);
        }
        return liveData;
    }

    /**
     * 在退出app的时候需要清除保存的LiveData否则下次进入会看到上次的数据
     * 可以在MainActivity的onDestroy方法中清调用
     */
    public static void release(){
        if(instance!=null){
            instance.maps.clear();
        }
    }

}
